package com.sky.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {
    private  static final String JSCODE_URL ="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    UserMapper userMapper;


    @Override
    public User login(UserLoginDTO userLoginDTO) {
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid","wxb7b71270c227e308");
        paramMap.put("secret","e60ffcfa9ef8a0427241815f02cc266c");
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");

        String result = HttpClientUtil.doGet(JSCODE_URL, paramMap);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = jsonObject.getString("openid");
        if (StringUtils.isEmpty(openid)) {
            throw new LoginFailedException("微信登录失败");
        }

        User user = userMapper.getByopenId(openid);
        if (user == null) {
            user = new User();
            user.setName("微信用户");
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }



        return user;
    }
}
